<template>
  <div class="page-container">
    <h2 class="page-title">推荐菜品管理</h2>

    <!-- 筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <el-form :inline="true">
        <el-form-item label="所属地点">
          <el-select
            v-model="queryParams.locationId"
            clearable
            placeholder="请选择地点"
            filterable
            style="width: 240px"
          >
            <el-option
              v-for="location in locations"
              :key="location.id"
              :label="location.name"
              :value="location.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">查询</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table v-loading="loading" :data="dishes" stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="菜品图片" width="100" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.imageUrl"
              :src="getFullImageUrl(row.imageUrl)"
              :preview-src-list="[getFullImageUrl(row.imageUrl)]"
              fit="cover"
              style="width: 60px; height: 60px; border-radius: 4px"
              :preview-teleported="true"
            />
            <span v-else class="text-muted">暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="dishName" label="菜品名称" min-width="150" show-overflow-tooltip />
        <el-table-column label="所属地点" min-width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag v-if="row.location" type="info">{{ row.location.name }}</el-tag>
            <span v-else class="text-muted">未知地点</span>
          </template>
        </el-table-column>
        <el-table-column prop="floor" label="售卖楼层" width="120">
          <template #default="{ row }">
            {{ row.floor || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="价格" width="100" align="right">
          <template #default="{ row }">
            <span v-if="row.price !== null" class="price-text">¥{{ row.price }}</span>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column label="推荐者" width="120">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar
                v-if="row.user?.avatarUrl"
                :src="row.user.avatarUrl"
                :size="24"
                style="margin-right: 8px"
              />
              <span>{{ row.user?.nickname || '匿名用户' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="viewDetail(row)">
              详情
            </el-button>
            <el-button type="danger" size="small" link @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleQuery"
          @current-change="handleQuery"
        />
      </div>
    </el-card>

    <!-- 详情抽屉 -->
    <el-drawer v-model="detailVisible" title="菜品详情" size="500px">
      <div v-if="currentDish" class="detail-content">
        <!-- 菜品图片 -->
        <div v-if="currentDish.imageUrl" class="dish-image-container">
          <el-image
            :src="getFullImageUrl(currentDish.imageUrl)"
            :preview-src-list="[getFullImageUrl(currentDish.imageUrl)]"
            fit="cover"
            style="width: 100%; border-radius: 8px"
            :preview-teleported="true"
          />
        </div>
        <div v-else class="no-image-placeholder">
          <span>暂无菜品图片</span>
        </div>

        <el-descriptions :column="1" border style="margin-top: 20px">
          <el-descriptions-item label="菜品名称">
            {{ currentDish.dishName }}
          </el-descriptions-item>
          <el-descriptions-item label="所属地点">
            <el-tag v-if="currentDish.location" type="info">
              {{ currentDish.location.name }}
            </el-tag>
            <span v-else>未知地点</span>
          </el-descriptions-item>
          <el-descriptions-item label="售卖楼层">
            {{ currentDish.floor || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="价格">
            <span v-if="currentDish.price !== null" class="price-text">
              ¥{{ currentDish.price }}
            </span>
            <span v-else>未设置</span>
          </el-descriptions-item>
          <el-descriptions-item label="推荐者">
            <div class="user-detail">
              <el-avatar
                v-if="currentDish.user?.avatarUrl"
                :src="currentDish.user.avatarUrl"
                :size="32"
              />
              <div class="user-text">
                <div>{{ currentDish.user?.nickname || '匿名用户' }}</div>
                <div class="text-muted">ID: {{ currentDish.userId }}</div>
              </div>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDate(currentDish.createdAt) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getDishes, deleteDish } from '@/api/dish'
import { getLocations } from '@/api/location'
import type { RecommendedDish, Location } from '@/types/api'
import { LocationStatus } from '@/types/api'
import { getFullImageUrl } from '@/utils/image'

// 状态定义
const loading = ref(false)
const dishes = ref<RecommendedDish[]>([])
const total = ref(0)
const detailVisible = ref(false)
const currentDish = ref<RecommendedDish | null>(null)
const locations = ref<Location[]>([])

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 20,
  locationId: undefined as number | undefined
})

/**
 * 加载地点列表(用于筛选下拉框)
 */
const loadLocations = async () => {
  try {
    const response = await getLocations({ status: LocationStatus.APPROVED, limit: 1000 })
    locations.value = response.data
  } catch (error) {
    console.error('加载地点列表失败:', error)
  }
}

/**
 * 加载菜品列表
 */
const loadDishes = async () => {
  loading.value = true
  try {
    const response = await getDishes(queryParams)
    dishes.value = response.data
    total.value = response.pagination?.total || 0
  } catch (error) {
    console.error('加载菜品列表失败:', error)
    ElMessage.error('加载菜品列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 查询按钮点击事件
 */
const handleQuery = () => {
  queryParams.page = 1
  loadDishes()
}

/**
 * 重置查询
 */
const resetQuery = () => {
  queryParams.page = 1
  queryParams.limit = 20
  queryParams.locationId = undefined
  loadDishes()
}

/**
 * 查看详情
 */
const viewDetail = (dish: RecommendedDish) => {
  currentDish.value = dish
  detailVisible.value = true
}

/**
 * 删除菜品
 */
const handleDelete = async (dish: RecommendedDish) => {
  try {
    await ElMessageBox.confirm(`确定要删除菜品"${dish.dishName}"吗?`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteDish(dish.locationId, dish.id)
    ElMessage.success('删除成功')
    loadDishes()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 格式化日期
 */
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 页面挂载时加载数据
onMounted(() => {
  loadLocations()
  loadDishes()
})
</script>

<style scoped>
.page-container {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  min-height: 400px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 16px;
}

.filter-card :deep(.el-card__body) {
  padding: 16px;
}

.table-card :deep(.el-card__body) {
  padding: 16px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.price-text {
  color: #f56c6c;
  font-weight: 600;
}

.text-muted {
  color: #909399;
  font-size: 12px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-detail {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-text {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.detail-content {
  padding: 0 16px;
}

.dish-image-container {
  width: 100%;
  max-height: 300px;
  overflow: hidden;
  border-radius: 8px;
  background: #f5f7fa;
}

.no-image-placeholder {
  width: 100%;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  border-radius: 8px;
  color: #909399;
  font-size: 14px;
}
</style>
